package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.appSecret}")
    private String appSecret;

    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code) {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", appSecret);
        map.put("js_code", code);
        JSONObject obj = JSONUtil.parseObj(HttpUtil.get(REQUEST_URL, map));
        if (ObjectUtil.isNotNull(obj.getInt("errcode"))) {
            throw new BaseException(obj.getStr("errmsg"));
        }
        return obj.getStr("openid");
    }

    /**
     * 获取手机号
     *
     * @param detailCode
     * @return
     */
    @Override
    public String getPhone(String detailCode) {
        String token = getToken();
        Map<String, Object> map = new HashMap<>();
        map.put("code", detailCode);
        String jsonStr = JSONUtil.toJsonStr(map);
        JSONObject obj = JSONUtil.parseObj(HttpUtil.post(PHONE_REQUEST_URL + token, jsonStr));
        if (obj.getInt("errcode") != 0) {
            throw new RuntimeException(obj.getStr("errmsg"));
        }
        return obj.getJSONObject("phone_info").getStr("phoneNumber");
    }

    public String getToken() {
        //获取token/
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", appSecret);
        JSONObject obj = JSONUtil.parseObj(HttpUtil.get(TOKEN_URL, map));
        if (ObjectUtil.isNotNull(obj.getInt("errcode"))) {
            throw new BaseException(obj.getStr("errmsg"));
        }
        String token = obj.getStr("access_token");
        return token;
    }
}
